<?php
include 'includes/db.php';
session_start();

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['code' => 1, 'desc' => 'Not logged in']);
    exit;
}

$user_id = $_SESSION['user_id'];
$cost = 0.50;

$stmt = $pdo->prepare("SELECT balance FROM users WHERE id = ?");
$stmt->execute([$user_id]);
$user = $stmt->fetch();

if ($user['balance'] < $cost) {
    echo json_encode(['code' => 1, 'desc' => 'Insufficient balance']);
    exit;
}

$new_balance = $user['balance'] - $cost;
$stmt = $pdo->prepare("UPDATE users SET balance = ? WHERE id = ?");
$stmt->execute([$new_balance, $user_id]);

$host = "https://qrymob.market.alicloudapi.com";
$path = "/lundear/telTwo";
$method = "GET";
$appcode = "1f094ffb216c438fb7e89ea99fdbaf14";
$headers = array();
array_push($headers, "Authorization:APPCODE " . $appcode);

$data = json_decode(file_get_contents('php://input'), true);
$mobile = $data['mobile'];
$name = urlencode($data['name']);

$querys = "mobile=" . $mobile . "&name=" . $name;
$url = $host . $path . "?" . $querys;

$curl = curl_init();
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_FAILONERROR, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);

$response = curl_exec($curl);
if (curl_errno($curl)) {
    echo json_encode(['code' => 1, 'desc' => 'CURL error: ' . curl_error($curl)]);
    curl_close($curl);
    exit;
}

curl_close($curl);

$result = json_decode($response, true);
echo json_encode($result);